package de.piratech.dasding.data.database.couch;

import java.util.ArrayList;
import java.util.List;

import org.ektorp.CouchDbConnector;
import org.ektorp.support.CouchDbRepositorySupport;

import de.piratech.dasding.data.User;
import de.piratech.dasding.data.database.UserData;
import de.piratech.dasding.data.database.couch.adapters.UserAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserDataImpl extends CouchDbRepositorySupport<UserAdapter>
        implements UserData {

  private static final Logger LOG = LoggerFactory.getLogger(UserData.class);

  public UserDataImpl(CouchDbConnector couchDbConnector) {
    super(UserAdapter.class, couchDbConnector, "User");
  }

  @Override
  public User createUser(User user) {
    LOG.debug("createUser({})", user);
    if (user instanceof UserAdapter) {
      add((UserAdapter) user);
      return user;
    } else {
      UserAdapter userAdap = new UserAdapter(user);
      add(userAdap);
      return userAdap;
    }
  }

  @Override
  public void deleteUser(String id) {
    LOG.debug("deleteUser({})", id);
    remove(get(id));
  }

  @Override
  public User updateUser(User user) {
    LOG.debug("updateUser({})", user);
    if (user instanceof UserAdapter) {
      update((UserAdapter) user);
      return user;
    }
    update(new UserAdapter(user));
    return user;
  }

  @Override
  public User getUser(String id) {
    LOG.debug("getUser({})", id);
    return get(id);
  }

  @Override
  public List<User> getUsers(String eventId) {
    LOG.debug("getUsers({})", eventId);
    return new ArrayList<User>(queryView("byEventId", eventId));
  }

  @Override
  public List<User> getUsers() {
     LOG.debug("getUsers()");
    return new ArrayList<User>(getAll());
  }
}
